import { computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useUserStore } from '@/store/user'

export function useUser() {
  const authStore = useAuthStore()
  const userStore = useUserStore()

  // 基本用户信息
  const userInfo = computed(() => authStore.userInfo)
  const username = computed(() => authStore.username)
  const avatar = computed(() => authStore.avatar)
  const accessToken = computed(() => authStore.accessToken)

  // 权限信息
  const permissions = computed(() => authStore.permissions)
  const perms = computed(() => authStore.perms)

  // 权限检查方法
  const hasPermission = (permission: string) => {
    return authStore.permissions.includes(permission)
  }

  const hasPerms = (perm: string) => {
    return authStore.perms.includes(perm)
  }

  // 是否已登录
  const isLoggedIn = computed(() => !!authStore.accessToken && !!authStore.username)

  // 获取用户显示名称
  const displayName = computed(() => {
    return authStore.username || '未知用户'
  })

  // 新增：根据用户ID获取用户名的功能
  const getStaticUserNameById = (id: string | undefined | null): string | null => {
    if (!id) return null
    return userStore.getUserNameByIdSync(id)
  }

  // 新增：根据用户ID获取用户信息
  const getStaticUserById = (id: string | undefined | null) => {
    if (!id) return undefined
    return userStore.getUserByIdSync(id)
  }

  // 新增：异步获取用户名（会自动刷新缓存）
  const getUserNameById = async (id: string | undefined | null): Promise<string> => {
    if (!id) return '未知用户'
    return await userStore.getUserNameById(id)
  }

  // 新增：异步获取用户信息（会自动刷新缓存）
  const getUserById = async (id: string | undefined | null) => {
    if (!id) return undefined
    return await userStore.getUserById(id)
  }

  return {
    // 用户信息
    userInfo,
    username,
    avatar,
    accessToken,
    displayName,

    // 权限信息
    permissions,
    perms,

    // 状态
    isLoggedIn,

    // 方法
    hasPermission,
    hasPerms,

    // 新增：用户名获取方法
    getStaticUserNameById,
    getStaticUserById,
    getUserNameById,
    getUserById,

    // 新增：所有用户列表（只读）
    allUsers: computed(() => userStore.allUsers),

    // 新增：用户数据管理方法
    loadAllUsers: userStore.loadAllUsers,
    refreshUsers: () => userStore.loadAllUsers(true)
  }
} 